<template>
  <el-dialog title="" custom-class="coupon-detail" :visible.sync="dialogVisible" fullscreen :show-close="false" @closed="onDialogClose">
    <el-form label-width="110px" ref="form" :model="formData" :rules="rules" :disabled="isDetail" size="small">
      <div class="base-info-box">
        <div class="base-info-left">
          <h2 class="mb15">基础信息</h2>
          <el-form-item label="优惠券名" prop="name">
            <el-input v-model="formData.name" maxlength="12" show-word-limit placeholder="请输入优惠券名称"/>
          </el-form-item>
          <el-form-item label="面值金额：" prop="amount">
            <el-input-number v-model="formData.amount"
            placeholder="请输入金额"
            style="width:250px"
            :precision="2"/>
          </el-form-item>
          <el-form-item label="门槛：" prop="threshold">
            <span class="mr10">满</span>
            <el-input-number v-model="formData.threshold"
              placeholder="请输入金额"
              controls-position="right"
              style="width:150px"
              :precision="0"/>
              <span class="ml10">元可用</span>
          </el-form-item>
          <el-form-item label="领取方式：" prop="draw_method">
            <el-radio-group v-model="formData.draw_method" @change="handleDrawMethodChange">
              <el-radio label="auto">自动领取</el-radio>
              <el-radio label="hand">手动领取</el-radio>
              <el-radio label="internal">平台推送</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="领取位置：" prop="show_pos">
            <el-checkbox-group v-model="formData.show_pos" :disabled="['auto', 'internal'].includes(formData.draw_method)">
              <el-checkbox label="draw_center">领券中心</el-checkbox>
              <el-checkbox label="feedback">卸载弹窗</el-checkbox>
              <el-checkbox label="scene">场景弹窗</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <!-- <el-form-item label="用户范围" prop="crowd">
            <el-checkbox-group v-model="formData.crowd">
              <p><el-checkbox label="not_buy">未购买</el-checkbox></p>
              <p class="mb15" style="font-size:14px">
                <el-checkbox label="is_vip">会员期间</el-checkbox>
                <el-checkbox label="vip_expire">会员过期</el-checkbox>
                <el-input-number v-model="formData.crowd_value.vip_expire_value"
                  placeholder="请输入"
                  controls-position="right"
                  :precision="0"
                  class="day-input ml15"/>
                <span class="ml10">天</span>
              </p>
              <p style="font-size:14px">
                <el-checkbox label="trialing">试用期间</el-checkbox>
                <el-checkbox label="trial_expire">试用过期</el-checkbox>
                <el-input-number v-model="formData.crowd_value.trial_expire_value"
                placeholder="请输入"
                controls-position="right"
                :precision="0"
                class="day-input ml15"/>
                <span class="ml10">天</span>
              </p>
            </el-checkbox-group>
          </el-form-item> -->
          <el-form-item label="描述" prop="describe">
            <el-input v-model="formData.describe"
              type="textarea"
              placeholder="请输入该优惠券的说明
此说明仅供内部运营人员阅读"
              :rows="3"/>
          </el-form-item>
        </div>
        <div class="base-info-right">
          <h2 class="mb15">使用规则</h2>
          <el-form-item label="发放时间" prop="show_time">
            <el-date-picker
              v-model="formData.show_time"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="停止发放时间" prop="stop_time">
            <el-date-picker
              v-model="formData.stop_time"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="生效时间">
            <el-radio-group v-model="formData.valid_type">
              <el-form-item label-width="0" prop="valid_time" style="margin-bottom: 22px;">
                <el-radio :label="1">固定期限</el-radio>
                <el-date-picker v-model="formData.valid_time"
                  type="datetimerange"
                  align="right"
                  class="ml10"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="['00:00:00', '23:59:59']"
                  value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
              </el-form-item>
              <el-form-item label-width="0" prop="valid_day">
                <el-radio :label="2">无固定期限</el-radio>
                <span class="mr10">领取后</span>
                <el-input-number v-model="formData.valid_day"
                  placeholder="请输入"
                  controls-position="right"
                  :precision="0"/>

                  <el-select
                    v-model="formData.valid_unit"
                    placeholder="请选择"
                    style="width: 80px;margin: 0 5px 0 10px;"
                  >
                    <el-option label="天" :value="1"/>
                    <el-option label="分钟" :value="2"/>
                  </el-select>

                  <span>内有效</span>
              </el-form-item>
            </el-radio-group>
          </el-form-item>
          <p class="mb15"></p>

          <el-form-item label="使用说明" prop="instruct">
            <el-input v-model="formData.instruct"
              type="textarea"
              placeholder="请输入该优惠券的使用规则
此说明将呈现在优惠券中供用户阅读
例：
1.不可与其他优惠券叠加使用
2.不可与其他活动同享优惠
3.……满XXX可用
4.如有疑问请联系客服：0755-XXXXXXX
5.本活动一切解释权归……"
              :rows="13"/>
          </el-form-item>
        </div>
      </div>
      <div class="app-info-box">
        <h2 class="mb15">应用范围</h2>
        <!-- <h2 class="mb15">产品范围</h2> -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="项目" prop="app_id">
              <select-check-box v-model="formData.app_id"
                @change="getUserGroupList"
                :selOptions="permission_projectList"
                :props="{value: 'app_id', label: 'name'}"
                style="width:250px">
              </select-check-box>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="渠道" prop="channel_id">
              <el-cascader
                v-model="formData.channel_id"
                :options="newChannelOptions"
                :props="{ multiple: true,emitPath:false }"
                collapse-tags
                :show-all-levels="false"
                clearable
                filterable
                style="width:250px"
                ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最低版本" prop="min_version">
              <el-input v-model="formData.min_version" type="text" placeholder="请输入最低版本"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="权益包" prop="right_package">
              <select-check-box v-model="formData.right_package"
                :selOptions="pkgList"
                :props="{value: 'package_id', label: 'name'}"
                checkAllLabel="全部业务"
                style="width:250px">
              </select-check-box>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户分群" prop="ug_ids">
              <el-select
                  multiple
                  filterable
                  v-model="formData.ug_ids"
                  @keydown.native.delete.capture.stop.prevent
                  style="width:250px"
                  collapse-tags
                  no-data-text="无数据,请尝试选择其他项目"
                  popper-class="mw500"
                  placeholder="请选择用户分群">
                  <el-option v-for="item in userGroupList"
                    :key="item.id"
                    :label="item.id+'  '+item.name"
                    :value="item.id"/>
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div class="coupon-detail-footer">
      <el-button type="primary" :loading="saveLoading" @click="onSubmit">确 认</el-button>
      <el-button @click="onDialogClose">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { mapGetters } from 'vuex'
import { listRightPackage } from '@/api/rights/package'
import { listUserGroup } from '@/api/user-clustering'
import { addCoupon, updateCoupon } from '@/api/coupon'
import { parseTime, formatMoney, toFixed } from '@/utils'
export default {
  name: 'ExchangeCodeDetail',
  props: {
    visible: Boolean,
    isDetail: Boolean,
    detailObj: {
      type: Object,
      default: () => {
        return {}
      }
    },
    channelOptions: {
      type: Array,
      default: () => []
    }
  },
  data () {
    const validateTime = (rule, value, callback) => {
      if (this.formData.valid_type === 1 && (!value || !value.length)) {
        callback(new Error('时间不能为空'))
      } else {
        callback()
      }
    }
    const validateDay = (rule, value, callback) => {
      if (this.formData.valid_type === 2 && !value) {
        callback(new Error('时间不能为空'))
      } else {
        callback()
      }
    }
    return {
      pkgList: [],
      userGroupList: [],
      saveLoading: false,
      formData: {
        name: '',
        amount: undefined,
        threshold: undefined,
        draw_method: 'auto',
        show_pos: ['draw_center'],
        // crowd: [],
        // crowd_value: {
        //   vip_expire_value: undefined,
        //   trial_expire_value: undefined
        // },
        show_time: '',
        stop_time: '',
        valid_type: 1,
        valid_time: [],
        valid_day: undefined,
        valid_unit: 1,
        instruct: '',
        right_package: [],
        app_id: [],
        channel_id: [],
        ug_ids: [],
        min_version: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '金额不能为空', trigger: 'blur' }
        ],
        // crowd: [
        //   { required: true, type: 'array', message: '用户范围不能为空', trigger: [] }
        // ],
        draw_method: [
          { required: true, message: '领取方式不能为空', trigger: [] }
        ],
        show_pos: [
          { required: true, type: 'array', message: '领取位置不能为空', trigger: [] }
        ],
        show_time: [
          { required: true, message: '发放时间不能为空', trigger: 'blur' }
        ],
        valid_time: [
          { validator: validateTime, trigger: 'blur' }
        ],
        valid_day: [
          { validator: validateDay, trigger: 'blur' }
        ],
        instruct: [{
          required: true, message: '请输入使用说明', trigger: 'blur'
        }],
        right_package: [
          { required: true, type: 'array', message: '权益包不能为空', trigger: 'blur' }
        ],
        ug_ids: [
          { max: 10, type: 'array', message: '最多可选10个用户分群', trigger: 'change' }
        ],
        app_id: [
          { required: true, type: 'array', message: '项目不能为空', trigger: 'blur' }
        ],
        channel_id: [
          { required: true, type: 'array', message: '渠道不能为空', trigger: 'blur' }
        ],
        min_version: [{
          required: true, message: '请输入最低版本', trigger: 'blur'
        }]
      }
    }
  },
  filters: {
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList']),
    dialogVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    channelOpts () {
      let list = []
      this.channelOptions.map(item => {
        list = list.concat(item.children)
      })
      return list
    },
    newChannelOptions () {
      return [...[{
        label: '所有渠道',
        value: 'all'
      }], ...this.channelOptions]
    }
  },
  watch: {
    dialogVisible (val) {
      if (val) {
        this.setSubParams()
      }
    }
  },
  async created () {
    listRightPackage({ page: 1, page_size: 100, status: 1 }).then(res => {
      this.pkgList = res.data.list || []
    })
  },
  methods: {
    handleDrawMethodChange (value) {
      if (value === 'auto' || value === 'internal') {
        this.formData.show_pos = ['draw_center']
      }
    },
    onSubmit () {
      if (this.isDetail) {
        this.onDialogClose()
        return
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          const params = this.getSubParams()
          let requestFn = addCoupon
          if (this.detailObj.id) {
            params.id = this.detailObj.id
            requestFn = updateCoupon
          }
          this.saveLoading = true

          requestFn(params).then(() => {
            this.onDialogClose()
            this.$message({
              type: 'success',
              message: this.detailObj.id ? '修改成功' : '创建成功'
            })
            this.$emit('listChange')
          }).finally(() => {
            this.saveLoading = false
          })
        }
      })
    },
    getUserGroupList () {
      listUserGroup({
        page: 1,
        page_size: 100,
        status: 'publish',
        appid: this.formData.app_id.join(',')
      }).then(res => {
        this.userGroupList = res.data.list || []
      })
    },
    getSubParams () {
      const params = {
        name: this.formData.name,
        c_type: 1,
        describe: this.formData.describe,
        draw_method: this.formData.draw_method,
        show_pos: this.formData.show_pos,
        instruct: this.formData.instruct,
        show_time: parseTime(this.formData.show_time, '{y}-{m}-{d}T{h}:{i}:{s}+08:00'),
        valid_type: this.formData.valid_type,
        valid_day: this.formData.valid_day,
        valid_unit: this.formData.valid_unit,
        right_package: this.formData.right_package,
        min_version: this.formData.min_version,
        ug_ids: this.formData.ug_ids,
        status: 0,
        app_id: this.formData.app_id,
        channel_id: this.formData.channel_id
      }
      if (this.formData.stop_time) {
        params.stop_time = parseTime(this.formData.stop_time, '{y}-{m}-{d}T{h}:{i}:{s}+08:00')
      }
      params.amount = toFixed(this.formData.amount * 100, 0)
      if (this.formData.threshold) params.threshold = toFixed(this.formData.threshold * 100, 0)
      if (this.formData.valid_time && this.formData.valid_time.length) {
        params.valid_start = this.formData.valid_time[0]
        params.valid_stop = this.formData.valid_time[1]
      }
      if (params.channel_id.includes('all')) {
        params.channel_id = []
      }
      return params
    },
    setSubParams () {
      if (!this.detailObj.id) return
      this.$nextTick(() => {
        this.formData = {
          name: this.detailObj.name,
          amount: formatMoney(this.detailObj.amount),
          threshold: formatMoney(this.detailObj.threshold),
          show_time: parseTime(this.detailObj.show_time),
          stop_time: this.detailObj.stop_time ? parseTime(this.detailObj.stop_time) : '',
          valid_type: this.detailObj.valid_type,
          valid_day: this.detailObj.valid_day,
          valid_unit: this.detailObj.valid_unit || 1,
          describe: this.detailObj.describe,
          instruct: this.detailObj.instruct,
          right_package: this.detailObj.right_package,
          min_version: this.detailObj.min_version,
          draw_method: this.detailObj.draw_method || '',
          show_pos: this.detailObj.show_pos,
          ug_ids: this.detailObj.ug_ids,
          valid_time: [],
          app_id: this.detailObj.app_id.map(item => item),
          channel_id: this.detailObj.channel_id.map(item => item)
        }
        if (this.detailObj.valid_start) this.formData.valid_time = [this.detailObj.valid_start, this.detailObj.valid_stop]
        if (!this.detailObj.app_id.length) this.formData.app_id = this.permission_projectList.map(item => item.app_id)
        if (!this.detailObj.channel_id.length) this.formData.channel_id = ['all']
        this.getUserGroupList()
      })
    },
    onDialogClose () {
      this.$refs.form.resetFields()
      this.formData.valid_unit = 1
      this.userGroupList = []
      this.dialogVisible = false
      // this.formData.crowd_value.vip_expire_value = undefined
      // this.formData.crowd_value.trial_expire_value = undefined
    }
  }

}
</script>
<style lang="scss" scoped>
.mb15{
  margin-bottom: 15px;
}
.mr10{
  margin-right: 10px;
}
.ml10{
  margin-left: 10px;
}
.ml15{
  margin-left: 15px;
}
.base-info-box{
  display: flex;
}
.app-info-box,.coupon-detail-footer{
  padding: 15px;
  margin-top: 10px;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba($color: #000, $alpha: 0.2);
}
.coupon-detail-footer{
  text-align: right;
}
.base-info-left,.base-info-right{
  flex: 1;
  padding: 15px 15px 0;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba($color: #000, $alpha: 0.2);
}
.base-info-right{
  margin-left: 10px;
}
.form-label{
  width: 88px;
  margin-bottom: 10px;
  text-align: right;
}
</style>
<style lang="scss">
.coupon-detail.is-fullscreen{
  background-color: #f5f5f5;
  .el-dialog__header{
    padding: 0;
  }
  .el-dialog__body{
    padding: 15px 20px;
  }
}
.base-info-box{
  .el-input{
    max-width: 400px;
  }
}
.day-input .el-input__inner{
  border-color: #DCDFE6!important;
}
.mw500 {
  max-width: 500px;
}
</style>
